﻿using System;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;

namespace Moe.ECamel.Client.WinForms.Controls
{
	public partial class ItemDetailsControl : ECamelUserControl
	{
		public ItemDetailsControl()
		{
			InitializeComponent();
		}

		private DetailsMode _detailsMode;
		public DetailsMode DetailsMode
		{
			get { return this._detailsMode; }
			set
			{
				this._detailsMode = value;
				ItemTypeComboBox.Enabled = (value == DetailsMode.Create);
				CatalogNumberTextBox.ReadOnly = (value == DetailsMode.View);
				TitleTextBox.ReadOnly = (value == DetailsMode.View);
				ItemPropertiesDataGridView.ReadOnly = (value == DetailsMode.View);
				ItemPropertiesBindingSource.AllowNew = (value != DetailsMode.View);
			}
		}
		public void Bind(Item entity)
		{
			ItemBindingSource.DataSource = entity;
			ItemPropertiesBindingSource.DataSource = entity.ItemProperties;
			ItemIdTextBox.Bind(ItemBindingSource, "ItemId");
			CatalogNumberTextBox.Bind(ItemBindingSource, "CatalogNumber");
			TitleTextBox.Bind(ItemBindingSource, "Title");
			ItemTypeComboBox.Bind(ItemBindingSource, "ItemTypeId", ECamelHelper.ItemTypesList, "ItemTypeName", "ItemTypeId");

			ItemPropertyTypesBindingSource.DataSource = ECamelHelper.ItemPropertyTypes;
			ItemPropertyTypeColumn.DisplayMember = "ItemPropertyTypeName";
			ItemPropertyTypeColumn.ValueMember = "ItemPropertyTypeId";
			ItemPropertyTypeColumn.DataPropertyName = "ItemPropertyTypeId";
			ItemPropertyTypeColumn.DataSource = ItemPropertyTypesBindingSource;

			RefreshPropertyTypeColumn(entity.ItemTypeId);
		}

		public void CancelEdit()
		{
			this.ItemBindingSource.CancelEdit();
		}

		private void ItemTypeComboBox_SelectionChangeCommitted(object sender, EventArgs e)
		{
			Item item = this.ItemBindingSource.DataSource as Item;
			int selectedItemTypeId = (int)ItemTypeComboBox.SelectedValue;
			if (selectedItemTypeId != item.ItemTypeId)
			{
				//item.ItemProperties.Clear();
				ItemPropertiesBindingSource.Clear();
				RefreshPropertyTypeColumn(selectedItemTypeId);
			}
		}

		private void RefreshPropertyTypeColumn(int itemTypeId)
		{
			ItemPropertyTypesBindingSource.Filter = "ItemTypeId=0 OR ItemTypeId=" + itemTypeId;
		}
	}
}